﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonLibrary.DataModel.WorkFlow;
using System.Data;
using CommonLibrary.DataModel.Form;
using Bukovics.Workflow.Hosting;
using ServiceApplication.Dao.WorkFlow;
using CommonLibrary.Wf.Common;
using System.Workflow.Activities;
using System.IO;
using System.Xml;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel;
using CommonLibrary.Wf.InterFace;
using System.Transactions;
using ServiceApplication.Service.WorkFlow.WorkflowDesignerApp;
using System.Workflow.Runtime.Hosting;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Basic;
using System.Threading;
using System.Data.SqlClient;
using ServiceApplication.Dao.Basic;
using CommonLibrary.Common;

namespace ServiceApplication.Service.WorkFlow
{
    public class WorkFlowService
    {
        WfDao wfDao = new WfDao();
        WfTemplateDao wfTemplateDao = new WfTemplateDao();
        WfInsDao wfInsDao = new WfInsDao();
        WfInsvalueDao wivDao = new WfInsvalueDao();
        BasicService bs = new BasicService();

        #region 工作流实例

        //   //旧的发起和审批方法 2013-01-06 mlh 注释
        //   public ResTag DoWfStart(WorkflowRuntimeManager wfrManager, int wfplate_id, int wfid,
        //StartParameter startParameter, List<WfInsvalueEntity> wivList, Dictionary<int, StateMachineWorkflowInstance> wfTempDic)
        //   {
        //       string stime = DateUtil.getStandardTimeBySecond();
        //       WfTemplateEntity wfplateEntity = wfTemplateDao.QueryEntity(wfplate_id);

        //       if (wfplateEntity == null) return new ResTag(false, " 未找到对应wf模板 ");


        //       Dictionary<string, object> sp = new Dictionary<string, object>();
        //       sp.Add("创建者", startParameter.createrInfo);
        //       sp.Add("insValue", startParameter.insValue);
        //       sp.Add("流程名称", startParameter.wfName);
        //       ChoiceClrxx nextClr = null;
        //       if (startParameter.firstClr != null)
        //       {
        //           nextClr = new ChoiceClrxx();
        //           nextClr.处理者类型 = startParameter.firstCllx;
        //           nextClr.处理人编码 = startParameter.firstClr;
        //           //如果是新指定的人员，则传入参数
        //           sp.Add("下一步处理人", nextClr);
        //       }

        //       try
        //       {
        //           WorkflowInstanceWrapper instanceWrapper = null;
        //           TransactionOptions option = new TransactionOptions();
        //           option.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
        //           using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
        //           {

        //               TextReader t1 = new StringReader(wfplateEntity.wfdefinition);
        //               TextReader t2 = new StringReader(wfplateEntity.wfrule);
        //               XmlReader reader = XmlReader.Create(t1);
        //               XmlReader reader2 = XmlReader.Create(t2);
        //               instanceWrapper = wfrManager.StartWorkflow(reader, reader2, sp);
        //               if (instanceWrapper == null) return null; //工作流发起失败

        //               #region 数据库操作: 发起人任务存储
        //               WfTaskEntity wfTaskFqr = new WfTaskEntity();
        //               wfTaskFqr.uniqueid = instanceWrapper.Id;
        //               wfTaskFqr.ptask_id = -1;
        //               wfTaskFqr.taskname = startParameter.wfName;//使用用户命名的任务名作为发起任务的名字
        //               wfTaskFqr.state = WfTaskState.TASK_START;
        //               wfTaskFqr.processresult = "";
        //               wfTaskFqr.processtype = TaskClrType.发起人.ToString();
        //               wfTaskFqr.processaddition = "";
        //               wfTaskFqr.user_id = startParameter.createrInfo.user_id;
        //               wfTaskFqr.fqrcode = startParameter.createrInfo.user_id;
        //               wfTaskFqr.starttime = stime;
        //               wfTaskFqr.checkintime = "";
        //               wfTaskFqr.endtime = stime;
        //               wfTaskFqr.days = 100;
        //               wfTaskFqr.task_clyj = "";
        //               wfTaskFqr.isread = 1;
        //               string ptaskid = TaskDao.Add(wfTaskFqr);
        //               #endregion

        //               #region 数据库操作: 实例存储
        //               WfInsEntity wfInstance = new WfInsEntity();
        //               wfInstance.uniqueid = instanceWrapper.Id;
        //               wfInstance.wf_id = wfid;
        //               wfInstance.insname = startParameter.wfName;
        //               wfInstance.user_id = startParameter.createrInfo.user_id;
        //               wfInstance.createdate = stime;
        //               wfInstance.lastdate = DateUtil.getStandardTimeBySecond();
        //               wfInstance.flow_state = 1;
        //               wfInstance.result = "未完成";
        //               wfInstance.sqlargs = startParameter.sqlargs == null ? "" : startParameter.sqlargs;
        //               wfInstance.ins_id = "INS" + CommonMethod.getUniqueid();
        //               wfInstance.clr_id = startParameter.clrid ?? ""; //2012-04-06 mlh +
        //               wfInstance.ins_care = 0; //2012-04-29 mlh +
        //               wfInstance.ins_descn = startParameter.ins_descn;
        //               wfInstance.ins_appendix = startParameter.wfappendix;//2012-06-26 mlh +
        //               wfInsDao.addIns(wfInstance);
        //               #endregion

        //               #region 数据库操作: 实例值存储
        //               if (wivList.Count != 0)
        //               {
        //                   foreach (var item in (List<WfInsvalueEntity>)wivList)
        //                   {
        //                       item.task_id = int.Parse(ptaskid);
        //                   }
        //                   wivDao.AddEntity(wivList);
        //               }
        //               #endregion
        //               #region 数据库操作: 下一步任务存储
        //               Thread.Sleep(1000);
        //               #region 工作流操作:发起工作流之后, 获取当前工作流执行到的状态
        //               StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(wfrManager.WorkflowRuntime, instanceWrapper.Id);
        //               EventDrivenActivity eda = stateInstance.CurrentState.Activities[0] as EventDrivenActivity;
        //               等待审批提交 waitingHandler = eda.Activities[0] as 等待审批提交;

        //               //第二步

        //               #endregion
        //               if (startParameter.firstClr == null)//如果未传入clr信息，即处理类型不是 ‘按人员’ 或者 ’由上一步人指定‘ ，则从模板里获取clr信息
        //               {
        //                   if (waitingHandler.处理人.处理者类型 == TaskClrType.发起人.ToString())
        //                   {
        //                       startParameter.firstClr = new int[] { startParameter.createrInfo.user_id };
        //                   }
        //                   //如果是按职务，已经在action中处理传入方法参数 sp 中
        //                   //else if (waitingHandler.处理人.处理者类型 == TaskClrType.按职务.ToString())//按职务
        //                   //{
        //                   //    string dutyname = waitingHandler.处理人.按职务;
        //                   //    var dutyEntity = bs.QueryDuty(dutyname);
        //                   //    var clrEntity = bs.QueryUserByTwo(dutyEntity.id, startParameter.createrInfo.dept_id);
        //                   //    if (clrEntity != null)
        //                   //        startParameter.nextYh = new int[] { clrEntity.id };
        //                   //}
        //                   //else
        //                   //{
        //                   //获得当前处理人
        //                   //startParameter.firstClr = waitingHandler.处理人.处理人编码;
        //                   //}
        //               }
        //               List<string> newtaskids = new List<string>();
        //               for (int i = 0; i < startParameter.firstClr.Length; i++)
        //               {
        //                   WfTaskEntity wfTask = new WfTaskEntity();
        //                   wfTask.uniqueid = instanceWrapper.Id;
        //                   wfTask.ptask_id = int.Parse(ptaskid);
        //                   wfTask.taskname = stateInstance.CurrentState.Name;  //当前状态的名称作为任务名称
        //                   wfTask.state = WfTaskState.TASK_UNDO;
        //                   wfTask.processresult = "";
        //                   wfTask.processtype = waitingHandler.处理人.处理者类型;
        //                   wfTask.processaddition = "";
        //                   wfTask.user_id = startParameter.firstClr[i];   //这里还要看!!!!, 上面if中已经判断并赋值
        //                   wfTask.fqrcode = startParameter.createrInfo.user_id;
        //                   wfTask.starttime = stime;
        //                   wfTask.checkintime = "";
        //                   wfTask.endtime = ""; //
        //                   wfTask.days = 100;
        //                   wfTask.task_clyj = ""; //mlh 2012-05-17 + 处理意见
        //                   wfTask.isread = 0;
        //                   newtaskids.Add(TaskDao.Add(wfTask));
        //               }


        //               //如果处理人只有一个，当前默认发起后第一步的发起人确认通过
        //               if (startParameter.firstClr.Length == 1)
        //               {
        //                   foreach (var item in wivList)
        //                   {
        //                       item.task_id = int.Parse(newtaskids[0]);
        //                   }
        //                   DoWfProcess(wfrManager, instanceWrapper.Id, startParameter.createrInfo, newtaskids[0], ptaskid, eda.Name, eda.Description, "", wivList, startParameter.secondClr, wfTempDic);
        //               }
        //               #endregion
        //               scope.Complete();
        //           }
        //           return new ResTag(true);
        //       }
        //       catch (Exception e)
        //       {
        //           return new ResTag(false, "发起失败");
        //       }


        //   }

        //   //taskname :对应eventdriven的name,task_des：:对应eventdriven的description
        //   public ResTag DoWfProcess(WorkflowRuntimeManager wfrManager, Guid instanceId, UserEntity fqrEntity, string task_id, string ptask_id, string eventd_name, string eventd_des, string curtask_clyj,
        //       List<WfInsvalueEntity> wivList, int[] clrs, Dictionary<int, StateMachineWorkflowInstance> wfTempDic)
        //   {
        //       var frq_staff = bs.QueryStaff(fqrEntity.staff_id);
        //       BillServer billserver = (wfrManager.WorkflowRuntime).GetService<ServiceApplication.Service.WorkFlow.BillServer>();
        //       //ManualWorkflowSchedulerService scheduler = wfrManager.WorkflowRuntime.GetService<ManualWorkflowSchedulerService>();

        //       StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(wfrManager.WorkflowRuntime, instanceId);
        //       //当前任务状态
        //       EventDrivenActivity edact = (EventDrivenActivity)stateInstance.CurrentState.Activities[eventd_name];// EventDriven
        //       HandleExternalEventActivity heva = (HandleExternalEventActivity)edact.EnabledActivities[0];//存储了下一步处理人信息

        //       WfEntity wfEntity = wfDao.QueryEntityByuniqueid(instanceId.ToString());
        //       WfInsEntity wfinsEntity = wfInsDao.queryInsEntity(instanceId.ToString());
        //       if (clrs == null || clrs.Length == 0)
        //       {
        //           //注释原因 如果是按权限处理则一定会传进来clrs，要么是找到对应权限的人，要么是重新指定人

        //           WfClrxxInfo nextClr = getNextClrxxByTaskName(wfTempDic,
        //               wfEntity.wftemplate_id, edact.Parent.Name, eventd_des);

        //           //下一步处理人
        //           if (nextClr != null && nextClr.clzType == TaskClrType.按权限.ToString())
        //           {
        //               string[] wfspqxnames = nextClr.AsQx;
        //               var dt_qx = WfSpqxQuery(wfspqxnames);
        //               var arr_qxid = dt_qx.AsEnumerable().Select(s => s.Field<int>("编码")).ToArray();
        //               DataTable dt_clr = null;

        //               if (!nextClr.IsSelfDept)
        //                   dt_clr = bs.QueryUserBySpqx(arr_qxid);
        //               else
        //                   dt_clr = bs.QueryUserBySpqxDept(arr_qxid, frq_staff.dept_id);

        //               //按职务的类型下如果有多人，则多人抢占式发起
        //               if (dt_clr != null && dt_clr.Rows.Count > 0)
        //               {
        //                   clrs = dt_clr.AsEnumerable().Select(d => d.Field<int>("用户编码")).ToArray();
        //               }
        //               else
        //               {
        //                   return new ResTag(false, "下一步处理人不存在，请确认");
        //               }
        //           }
        //           else if (nextClr != null && nextClr.clzType == TaskClrType.发起人.ToString())
        //           {
        //               clrs = new int[] { fqrEntity.user_id };
        //           }
        //           else if (nextClr != null && nextClr.clzType == TaskClrType.按人员.ToString())
        //           {
        //               clrs = nextClr.clrCode;
        //           }
        //       }
        //       WfTaskEntity wfTaskEntity = TaskDao.Query(task_id);

        //       #region 事务操作: 先触发工作流，再存入数据库
        //       TransactionOptions option = new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted };
        //       using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
        //       {
        //           List<WfTaskEntity> taskEntityNewlist = new List<WfTaskEntity>();

        //           var task_refuse = this.taskRefuse(wfTempDic, wfEntity.wftemplate_id, edact.Parent.Name, eventd_des);

        //           billserver.RaiseEvent(heva.EventName, new ReceivedEventArgs(instanceId, fqrEntity, clrs, "taskname", wivList));  //这里fqr可能没传好，目前未发现任何影响 mlh 
        //           Thread.Sleep(3000);//要修改，应该获取工作流是否完成再进行下面操作

        //           if (null != stateInstance.CurrentState)   //如果还没结束
        //           {
        //               // 工作流操作:  获取当前工作流执行到的状态
        //               EventDrivenActivity eda = stateInstance.CurrentState.Activities[0] as EventDrivenActivity;
        //               等待审批提交 waitingHandler = null;
        //               if (eda != null)
        //               {
        //                   waitingHandler = eda.Activities[0] as 等待审批提交;
        //               }
        //               if (!task_refuse)
        //               {
        //                   #region 非驳回流程-数据获取: 新任务实体taskEntityNew
        //                   WfTaskEntity taskEntity = QueryTask(task_id);
        //                   if (clrs != null) //如果nextClrInfo.clrCode==null 则说明下一步结束了,待验证 mlh 2011-11-21
        //                   {
        //                       for (int i = 0; i < clrs.Length; i++)
        //                       {
        //                           taskEntityNewlist.Add(new WfTaskEntity()
        //                           {
        //                               ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
        //                               uniqueid = instanceId,
        //                               taskname = eda.Parent.Name,
        //                               state = WfTaskState.TASK_UNDO,
        //                               processresult = "",
        //                               processtype = waitingHandler.处理人.处理者类型,
        //                               processaddition = "无",
        //                               user_id = clrs[i],
        //                               fqrcode = taskEntity.fqrcode,
        //                               starttime = taskEntity.starttime,
        //                               checkintime = DateUtil.getStandardTimeBySecond(),
        //                               days = 100,
        //                               endtime = DateUtil.getStandardTimeBySecond(),
        //                               task_clyj = "",
        //                               isread = 0
        //                           });
        //                       }
        //                   }
        //                   else
        //                   {
        //                       if (waitingHandler.处理人.处理者类型 == TaskClrType.发起人.ToString())
        //                       {
        //                           clrs = new int[] { taskEntity.fqrcode };
        //                       }
        //                       else if (null != waitingHandler.处理人.处理人编码)
        //                       {
        //                           //获得当前处理人
        //                           clrs = waitingHandler.处理人.处理人编码;
        //                       }

        //                       if (null != clrs)
        //                       {
        //                           for (int i = 0; i < clrs.Length; i++)
        //                           {
        //                               taskEntityNewlist.Add(new WfTaskEntity()
        //                               {
        //                                   ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
        //                                   uniqueid = instanceId,
        //                                   taskname = eda.Parent.Name,
        //                                   state = WfTaskState.TASK_UNDO,
        //                                   processresult = "",
        //                                   processtype = waitingHandler.处理人.处理者类型,
        //                                   processaddition = "无",
        //                                   user_id = clrs[i],
        //                                   fqrcode = taskEntity.fqrcode,
        //                                   starttime = taskEntity.starttime,
        //                                   checkintime = "",
        //                                   days = 100,
        //                                   endtime = "",  //mlh 2011-11-21 + 
        //                                   task_clyj = "",
        //                                   isread = 0
        //                               });
        //                           }
        //                       }
        //                   }
        //                   #endregion
        //               }
        //               else
        //               {
        //                   #region 驳回流程

        //                   var pre_task = QueryTaskByName(instanceId.ToString(), eda.Parent.Name);//taskname从 edact.Parent.Name获取
        //                   taskEntityNewlist.Add(new WfTaskEntity()
        //                   {
        //                       ptask_id = int.Parse(task_id),
        //                       uniqueid = instanceId,
        //                       taskname = pre_task.Rows[0]["任务名称"].ToString(),
        //                       state = WfTaskState.TASK_UNDO,
        //                       processresult = "",
        //                       processtype = pre_task.Rows[0]["处理类型"].ToString(),
        //                       processaddition = pre_task.Rows[0]["处理备注"].ToString(),
        //                       user_id = Int32.Parse(pre_task.Rows[0]["处理人编码"].ToString()),
        //                       fqrcode = Int32.Parse(pre_task.Rows[0]["发起人编号"].ToString()),
        //                       starttime = DateUtil.getStandardTimeBySecond(),
        //                       checkintime = "",
        //                       days = 100,
        //                       endtime = "",
        //                       task_clyj = "",
        //                       isread = 0
        //                   });

        //                   #endregion
        //               }
        //               //如果当前表单需要短信提示，循环遍历新任务发送短信
        //               if (wfEntity.wf_dxbz == 1)
        //               {
        //                   for (int i = 0; i < taskEntityNewlist.Count; i++)
        //                   {
        //                       var clr_staff = bs.QueryStaffByUserId(taskEntityNewlist[i].user_id);
        //                       if (clr_staff == null || string.IsNullOrEmpty(clr_staff.staff_mobile)) continue;

        //                       string content = string.Format("您有一条新的审批任务:{0}.发起人:{1}.任务到达时间:{2}", wfinsEntity.insname, frq_staff.staff_name, DateUtil.getStandardTimeBySecond());
        //                       SMSHelper.DoSendMsg(clr_staff.staff_mobile, content);
        //                   }
        //               }
        //               AddTask(taskEntityNewlist);
        //               addInsvalue(wivList);
        //           }
        //           else  //工作流结束
        //           {
        //               updateInsResult(instanceId.ToString(), "结束", wfrManager);
        //           }
        //           string clsj = DateUtil.getStandardTimeBySecond();
        //           UpdateTask(task_id, ptask_id, instanceId, eventd_des, curtask_clyj, clsj, "");//暂时使用eventdriven的description属性作为处理结果
        //           scope.Complete();
        //       }
        //       return new ResTag(true, "操作成功");
        //       #endregion
        //   }

        //   public ResTag DoWfProcess2(WorkflowRuntimeManager wfrManager, Guid instanceId, UserEntity fqrEntity, string task_id, string ptask_id, string eventd_name, string eventd_des, string curtask_clyj,
        //    List<WfInsvalueEntity> wivList, int[] clrs, Dictionary<int, StateMachineWorkflowInstance> wfTempDic, string str_id)
        //   {
        //       var frq_staff = bs.QueryStaff(fqrEntity.staff_id);
        //       BillServer billserver = (wfrManager.WorkflowRuntime).GetService<ServiceApplication.Service.WorkFlow.BillServer>();
        //       //ManualWorkflowSchedulerService scheduler = wfrManager.WorkflowRuntime.GetService<ManualWorkflowSchedulerService>();

        //       //StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(wfrManager.WorkflowRuntime, instanceId);
        //       //当前任务状态
        //       //EventDrivenActivity edact = (EventDrivenActivity)stateInstance.CurrentState.Activities[eventd_name];// EventDriven
        //       //HandleExternalEventActivity heva = (HandleExternalEventActivity)edact.EnabledActivities[0];//存储了下一步处理人信息

        //       WfEntity wfEntity = wfDao.QueryEntityByuniqueid(instanceId.ToString());
        //       WfTaskEntity wftaskEntity = QueryTask(task_id);

        //       if (clrs == null || clrs.Length == 0)
        //       {
        //           //注释原因 如果是按权限处理则一定会传进来clrs，要么是找到对应权限的人，要么是重新指定人

        //           WfClrxxInfo nextClr = getNextClrxxByTaskName(wfTempDic, wfEntity.wftemplate_id, wftaskEntity.taskname, eventd_des);

        //           //下一步处理人
        //           if (nextClr != null && nextClr.clzType == TaskClrType.按权限.ToString())
        //           {
        //               string[] wfspqxnames = nextClr.AsQx;
        //               var dt_qx = WfSpqxQuery(wfspqxnames);
        //               var arr_qxid = dt_qx.AsEnumerable().Select(s => s.Field<int>("编码")).ToArray();
        //               DataTable dt_clr = null;

        //               if (!nextClr.IsSelfDept)
        //                   dt_clr = bs.QueryUserBySpqx(arr_qxid);
        //               else
        //                   dt_clr = bs.QueryUserBySpqxDept(arr_qxid, frq_staff.dept_id);

        //               //按职务的类型下如果有多人，则多人抢占式发起
        //               if (dt_clr != null && dt_clr.Rows.Count > 0)
        //               {
        //                   clrs = dt_clr.AsEnumerable().Select(d => d.Field<int>("用户编码")).ToArray();
        //               }
        //               else
        //               {
        //                   return new ResTag(false, "下一步处理人不存在，请确认");
        //               }
        //           }
        //           else if (nextClr != null && nextClr.clzType == TaskClrType.发起人.ToString())
        //           {
        //               clrs = new int[] { fqrEntity.user_id };
        //           }
        //           else if (nextClr != null && nextClr.clzType == TaskClrType.按人员.ToString())
        //           {
        //               clrs = nextClr.clrCode;
        //           }
        //       }
        //       WfTaskEntity wfTaskEntity = TaskDao.Query(task_id);

        //       #region 事务操作: 先触发工作流，再存入数据库
        //       TransactionOptions option = new TransactionOptions();
        //       option.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
        //       using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
        //       {
        //           List<WfTaskEntity> taskEntityNewlist = new List<WfTaskEntity>();

        //           var task_refuse = this.taskRefuse(wfTempDic, wfEntity.wftemplate_id, wftaskEntity.taskname, eventd_des);
        //           StateMachineWorkflowInstance workflowInstance = wfTempDic[wfEntity.wftemplate_id];

        //           等待审批提交 waitingHandler = WfUtil.getNextStateEventriven4agree(workflowInstance, wftaskEntity.taskname, eventd_des);
        //           if (null != waitingHandler)   //暂时用waitingHandler=null 来判断下一步是否是结束状态 2012-09-05 mlh
        //           {
        //               if (!task_refuse)
        //               {
        //                   #region 非驳回流程-数据获取: 新任务实体taskEntityNew
        //                   WfTaskEntity taskEntity = QueryTask(task_id);
        //                   if (clrs != null) //如果nextClrInfo.clrCode==null 则说明下一步结束了,待验证 mlh 2011-11-21
        //                   {
        //                       for (int i = 0; i < clrs.Length; i++)
        //                       {
        //                           taskEntityNewlist.Add(new WfTaskEntity()
        //                           {
        //                               ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
        //                               uniqueid = instanceId,
        //                               taskname = waitingHandler.Parent.Parent.Name,
        //                               state = WfTaskState.TASK_UNDO,
        //                               processresult = "",
        //                               processtype = waitingHandler.处理人.处理者类型,
        //                               processaddition = "无",
        //                               user_id = clrs[i],
        //                               fqrcode = taskEntity.fqrcode,
        //                               starttime = taskEntity.starttime,
        //                               checkintime = DateUtil.getStandardTimeBySecond(),
        //                               days = 100,
        //                               endtime = DateUtil.getStandardTimeBySecond(),
        //                               task_clyj = "",
        //                               isread = 0
        //                           });
        //                       }
        //                   }
        //                   else
        //                   {
        //                       if (waitingHandler.处理人.处理者类型 == TaskClrType.发起人.ToString())
        //                       {
        //                           clrs = new int[] { taskEntity.fqrcode };
        //                       }
        //                       else if (null != waitingHandler.处理人.处理人编码)
        //                       {
        //                           //获得当前处理人
        //                           clrs = waitingHandler.处理人.处理人编码;
        //                       }

        //                       if (null != clrs)
        //                       {
        //                           for (int i = 0; i < clrs.Length; i++)
        //                           {
        //                               taskEntityNewlist.Add(new WfTaskEntity()
        //                               {
        //                                   ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
        //                                   uniqueid = instanceId,
        //                                   taskname = waitingHandler.Parent.Parent.Name,
        //                                   state = WfTaskState.TASK_UNDO,
        //                                   processresult = "",
        //                                   processtype = waitingHandler.处理人.处理者类型,
        //                                   processaddition = "无",
        //                                   user_id = clrs[i],
        //                                   fqrcode = taskEntity.fqrcode,
        //                                   starttime = taskEntity.starttime,
        //                                   checkintime = "",
        //                                   days = 100,
        //                                   endtime = "",  //mlh 2011-11-21 + 
        //                                   task_clyj = "",
        //                                   isread = 0
        //                               });
        //                           }
        //                       }
        //                   }
        //                   #endregion
        //               }
        //               else
        //               {
        //                   #region 驳回流程

        //                   var pre_task = QueryTaskByName(instanceId.ToString(), waitingHandler.Parent.Parent.Name);//taskname从 edact.Parent.Name获取
        //                   taskEntityNewlist.Add(new WfTaskEntity()
        //                   {
        //                       ptask_id = int.Parse(task_id),
        //                       uniqueid = instanceId,
        //                       taskname = pre_task.Rows[0]["任务名称"].ToString(),
        //                       state = WfTaskState.TASK_UNDO,
        //                       processresult = "",
        //                       processtype = pre_task.Rows[0]["处理类型"].ToString(),
        //                       processaddition = pre_task.Rows[0]["处理备注"].ToString(),
        //                       user_id = Int32.Parse(pre_task.Rows[0]["处理人编码"].ToString()),
        //                       fqrcode = Int32.Parse(pre_task.Rows[0]["发起人编号"].ToString()),
        //                       starttime = DateUtil.getStandardTimeBySecond(),
        //                       checkintime = "",
        //                       days = 100,
        //                       endtime = "",
        //                       task_clyj = "",
        //                       isread = 0
        //                   });

        //                   #endregion
        //               }
        //               AddTask(taskEntityNewlist);
        //               addInsvalue(wivList);
        //           }
        //           else  //工作流结束
        //           {
        //               updateInsResult(instanceId.ToString(), "结束", wfrManager);
        //           }
        //           string clsj = DateUtil.getStandardTimeBySecond();
        //           UpdateTask(task_id, ptask_id, instanceId, eventd_des, curtask_clyj, clsj, str_id);//暂时使用eventdriven的description属性作为处理结果
        //           scope.Complete();
        //       }
        //       return new ResTag(true, "操作成功");
        //       #endregion
        //   }

        #region 只用模板

        public ResTag DoWfStart(WorkflowRuntimeManager wfrManager, int wfplate_id, int wfid,
     StartParameter startParameter, List<WfInsvalueEntity> wivList, Dictionary<int, StateMachineWorkflowInstance> wfTempDic)
        {
            string stime = DateUtil.getStandardTimeBySecond();
            WfTemplateEntity wfplateEntity = wfTemplateDao.QueryEntity(wfplate_id);

            if (wfplateEntity == null) return new ResTag(false, " 未找到对应wf模板 ");


            Dictionary<string, object> sp = new Dictionary<string, object>();
            sp.Add("创建者", startParameter.createrInfo);
            sp.Add("insValue", startParameter.insValue);
            sp.Add("流程名称", startParameter.wfName);
            ChoiceClrxx nextClr = null;
            if (startParameter.firstClr != null)
            {
                nextClr = new ChoiceClrxx();
                nextClr.处理者类型 = startParameter.firstCllx;
                nextClr.处理人编码 = startParameter.firstClr;
                //如果是新指定的人员，则传入参数
                sp.Add("下一步处理人", nextClr);
            }

            //try
            //{
            Guid uniqueid = Guid.NewGuid();
            TransactionOptions option = new TransactionOptions();
            option.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
            {

                #region 数据库操作: 实例存储
                WfInsEntity wfInstance = new WfInsEntity();
                wfInstance.uniqueid = uniqueid; //instanceWrapper.Id;
                wfInstance.wf_id = wfid;
                wfInstance.insname = startParameter.wfName;
                wfInstance.user_id = startParameter.createrInfo.user_id;
                wfInstance.createdate = stime;
                wfInstance.lastdate = DateUtil.getStandardTimeBySecond();
                wfInstance.flow_state = 1;
                wfInstance.result = "未完成";
                wfInstance.sqlargs = startParameter.sqlargs == null ? "" : startParameter.sqlargs;
                wfInstance.ins_id = "INS" + CommonMethod.getUniqueid();
                wfInstance.clr_id = startParameter.clrid ?? ""; //2012-04-06 mlh +
                wfInstance.ins_care = 0; //2012-04-29 mlh +
                wfInstance.ins_descn = startParameter.ins_descn;
                wfInstance.ins_appendix = startParameter.wfappendix;//2012-06-26 mlh +
                wfInsDao.addIns(wfInstance);
                #endregion

                #region 数据库操作: 发起人任务存储
                WfTaskEntity wfTaskFqr = new WfTaskEntity();
                wfTaskFqr.uniqueid = uniqueid; //instanceWrapper.Id;
                wfTaskFqr.ptask_id = -1;
                wfTaskFqr.taskname = startParameter.wfName;//使用用户命名的任务名作为发起任务的名字
                wfTaskFqr.state = WfTaskState.TASK_START;
                wfTaskFqr.processresult = "";
                wfTaskFqr.processtype = TaskClrType.发起人.ToString();
                wfTaskFqr.processaddition = "";
                wfTaskFqr.user_id = startParameter.createrInfo.user_id;
                wfTaskFqr.fqrcode = startParameter.createrInfo.user_id;
                wfTaskFqr.starttime = stime;
                wfTaskFqr.checkintime = "";
                wfTaskFqr.endtime = stime;
                wfTaskFqr.days = 100;
                wfTaskFqr.task_clyj = "";
                wfTaskFqr.isread = 1;
                string ptaskid = TaskDao.Add(wfTaskFqr);
                #endregion

                #region 数据库操作: 实例值存储
                if (wivList.Count != 0)
                {
                    foreach (var item in (List<WfInsvalueEntity>)wivList)
                    {
                        item.task_id = int.Parse(ptaskid);
                    }
                    wivDao.AddEntity(wivList);
                }
                #endregion

                StateMachineWorkflowInstance stateInstance = wfTempDic[wfplate_id] as StateMachineWorkflowInstance;
                var firstState = WfUtil.getFirstState(stateInstance);
                var eda = WfUtil.getEda4Agree(firstState);
                var clrxx_plate = WfUtil.getClrxx4Agree(firstState);

                #region 第二步

                if (startParameter.firstClr == null)//如果未传入clr信息，即处理类型不是 ‘按人员’ 或者 ’由上一步人指定‘ ，则从模板里获取clr信息
                {
                    if (clrxx_plate.处理者类型 == TaskClrType.发起人.ToString())
                    {
                        startParameter.firstClr = new int[] { startParameter.createrInfo.user_id };
                    }
                }
                List<string> newtaskids = new List<string>();
                for (int i = 0; i < startParameter.firstClr.Length; i++)
                {
                    WfTaskEntity wfTask = new WfTaskEntity();
                    wfTask.uniqueid = uniqueid;//instanceWrapper.Id;
                    wfTask.ptask_id = int.Parse(ptaskid);
                    wfTask.taskname = firstState.Name;  //状态的名称作为任务名称
                    wfTask.state = WfTaskState.TASK_UNDO;
                    wfTask.processresult = "";
                    wfTask.processtype = clrxx_plate.处理者类型;
                    wfTask.processaddition = "";
                    wfTask.user_id = startParameter.firstClr[i];   //这里还要看!!!!, 上面if中已经判断并赋值
                    wfTask.fqrcode = startParameter.createrInfo.user_id;
                    wfTask.starttime = stime;
                    wfTask.checkintime = "";
                    wfTask.endtime = ""; //
                    wfTask.days = 100;
                    wfTask.task_clyj = ""; //mlh 2012-05-17 + 处理意见
                    wfTask.isread = 0;
                    newtaskids.Add(TaskDao.Add(wfTask));
                }


                //如果处理人只有一个，当前默认发起后第一步的发起人确认通过
                if (startParameter.firstClr.Length == 1)
                {
                    foreach (var item in wivList)
                    {
                        item.task_id = int.Parse(newtaskids[0]);
                    }
                    DoWfProcess2(wfrManager, uniqueid, startParameter.createrInfo, newtaskids[0], ptaskid, eda.Name, eda.Description, "", wivList, startParameter.secondClr, wfTempDic, null);
                }
                #endregion


                scope.Complete();
            }
            return new ResTag(true);
            //}
            //catch (Exception e)
            //{
            //    return new ResTag(false, "发起失败");
            //}
        }

        //taskname :对应eventdriven的name,task_des：:对应eventdriven的description
        public ResTag DoWfProcess(WorkflowRuntimeManager wfrManager, Guid instanceId, UserEntity fqrEntity, string task_id, string ptask_id, string eventd_name, string eventd_des, string curtask_clyj,
            List<WfInsvalueEntity> wivList, int[] clrs, Dictionary<int, StateMachineWorkflowInstance> wfTempDic)
        {
            var frq_staff = bs.QueryStaff(fqrEntity.staff_id);
            WfEntity wfEntity = wfDao.QueryEntityByuniqueid(instanceId.ToString());
            WfInsEntity wfinsEntity = wfInsDao.queryInsEntity(instanceId.ToString());

            StateMachineWorkflowInstance stateInstance = wfTempDic[wfEntity.wftemplate_id] as StateMachineWorkflowInstance;
            //对应当前任务状态
            EventDrivenActivity edact = (EventDrivenActivity)stateInstance.CurrentState.Activities[eventd_name];// EventDriven
            HandleExternalEventActivity heva = (HandleExternalEventActivity)edact.EnabledActivities[0];//存储了下一步处理人信息


            if (clrs == null || clrs.Length == 0)
            {
                //注释原因 如果是按权限处理则一定会传进来clrs，要么是找到对应权限的人，要么是重新指定人

                WfClrxxInfo nextClr = getNextClrxxByTaskName(wfTempDic,
                    wfEntity.wftemplate_id, edact.Parent.Name, eventd_des);

                //下一步处理人
                if (nextClr != null && nextClr.clzType == TaskClrType.按权限.ToString())
                {
                    string[] wfspqxnames = nextClr.AsQx;
                    var dt_qx = WfSpqxQuery(wfspqxnames);
                    var arr_qxid = dt_qx.AsEnumerable().Select(s => s.Field<int>("编码")).ToArray();
                    DataTable dt_clr = null;

                    if (!nextClr.IsSelfDept)
                        dt_clr = bs.QueryUserBySpqx(arr_qxid);
                    else
                        dt_clr = bs.QueryUserBySpqxDept(arr_qxid, frq_staff.dept_id);

                    //按职务的类型下如果有多人，则多人抢占式发起
                    if (dt_clr != null && dt_clr.Rows.Count > 0)
                    {
                        clrs = dt_clr.AsEnumerable().Select(d => d.Field<int>("用户编码")).ToArray();
                    }
                    else
                    {
                        return new ResTag(false, "下一步处理人不存在，请确认");
                    }
                }
                else if (nextClr != null && nextClr.clzType == TaskClrType.发起人.ToString())
                {
                    clrs = new int[] { fqrEntity.user_id };
                }
                else if (nextClr != null && nextClr.clzType == TaskClrType.按人员.ToString())
                {
                    clrs = nextClr.clrCode;
                }
            }
            WfTaskEntity wfTaskEntity = TaskDao.Query(task_id);

            #region 事务操作: 先触发工作流，再存入数据库
            TransactionOptions option = new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted };
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
            {
                List<WfTaskEntity> taskEntityNewlist = new List<WfTaskEntity>();

                var task_refuse = this.taskRefuse(wfTempDic, wfEntity.wftemplate_id, edact.Parent.Name, eventd_des);

                if (null != stateInstance.CurrentState)   //如果还没结束
                {
                    // 工作流操作:  获取当前工作流执行到的状态
                    EventDrivenActivity eda = stateInstance.CurrentState.Activities[0] as EventDrivenActivity;
                    等待审批提交 waitingHandler = null;
                    if (eda != null)
                    {
                        waitingHandler = eda.Activities[0] as 等待审批提交;
                    }
                    if (!task_refuse)
                    {
                        #region 非驳回流程-数据获取: 新任务实体taskEntityNew
                        WfTaskEntity taskEntity = QueryTask(task_id);
                        if (clrs != null) //如果nextClrInfo.clrCode==null 则说明下一步结束了,待验证 mlh 2011-11-21
                        {
                            for (int i = 0; i < clrs.Length; i++)
                            {
                                taskEntityNewlist.Add(new WfTaskEntity()
                                {
                                    ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
                                    uniqueid = instanceId,
                                    taskname = eda.Parent.Name,
                                    state = WfTaskState.TASK_UNDO,
                                    processresult = "",
                                    processtype = waitingHandler.处理人.处理者类型,
                                    processaddition = "无",
                                    user_id = clrs[i],
                                    fqrcode = taskEntity.fqrcode,
                                    starttime = taskEntity.starttime,
                                    checkintime = DateUtil.getStandardTimeBySecond(),
                                    days = 100,
                                    endtime = DateUtil.getStandardTimeBySecond(),
                                    task_clyj = "",
                                    isread = 0
                                });
                            }
                        }
                        else
                        {
                            if (waitingHandler.处理人.处理者类型 == TaskClrType.发起人.ToString())
                            {
                                clrs = new int[] { taskEntity.fqrcode };
                            }
                            else if (null != waitingHandler.处理人.处理人编码)
                            {
                                //获得当前处理人
                                clrs = waitingHandler.处理人.处理人编码;
                            }

                            if (null != clrs)
                            {
                                for (int i = 0; i < clrs.Length; i++)
                                {
                                    taskEntityNewlist.Add(new WfTaskEntity()
                                    {
                                        ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
                                        uniqueid = instanceId,
                                        taskname = eda.Parent.Name,
                                        state = WfTaskState.TASK_UNDO,
                                        processresult = "",
                                        processtype = waitingHandler.处理人.处理者类型,
                                        processaddition = "无",
                                        user_id = clrs[i],
                                        fqrcode = taskEntity.fqrcode,
                                        starttime = taskEntity.starttime,
                                        checkintime = "",
                                        days = 100,
                                        endtime = "",  //mlh 2011-11-21 + 
                                        task_clyj = "",
                                        isread = 0
                                    });
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region 驳回流程

                        var pre_task = QueryTaskByName(instanceId.ToString(), eda.Parent.Name);//taskname从 edact.Parent.Name获取
                        taskEntityNewlist.Add(new WfTaskEntity()
                        {
                            ptask_id = int.Parse(task_id),
                            uniqueid = instanceId,
                            taskname = pre_task.Rows[0]["任务名称"].ToString(),
                            state = WfTaskState.TASK_UNDO,
                            processresult = "",
                            processtype = pre_task.Rows[0]["处理类型"].ToString(),
                            processaddition = pre_task.Rows[0]["处理备注"].ToString(),
                            user_id = Int32.Parse(pre_task.Rows[0]["处理人编码"].ToString()),
                            fqrcode = Int32.Parse(pre_task.Rows[0]["发起人编号"].ToString()),
                            starttime = DateUtil.getStandardTimeBySecond(),
                            checkintime = "",
                            days = 100,
                            endtime = "",
                            task_clyj = "",
                            isread = 0
                        });

                        #endregion
                    }
                    //如果当前表单需要短信提示，循环遍历新任务发送短信
                    if (wfEntity.wf_dxbz == 1)
                    {
                        for (int i = 0; i < taskEntityNewlist.Count; i++)
                        {
                            var clr_staff = bs.QueryStaffByUserId(taskEntityNewlist[i].user_id);
                            if (clr_staff == null || string.IsNullOrEmpty(clr_staff.staff_mobile)) continue;

                            string content = string.Format("您有一条新的审批任务:{0}.发起人:{1}.任务到达时间:{2}", wfinsEntity.insname, frq_staff.staff_name, DateUtil.getStandardTimeBySecond());
                            SMSHelper.DoSendMsg(clr_staff.staff_mobile, content);
                        }
                    }
                    AddTask(taskEntityNewlist);
                    addInsvalue(wivList);
                }
                else  //工作流结束
                {
                    updateInsResult(instanceId.ToString(), "结束", wfrManager);
                }
                string clsj = DateUtil.getStandardTimeBySecond();
                UpdateTask(task_id, ptask_id, instanceId, eventd_des, curtask_clyj, clsj, "");//暂时使用eventdriven的description属性作为处理结果
                scope.Complete();
            }
            return new ResTag(true, "操作成功");
            #endregion
        }


        public ResTag DoWfProcess2(WorkflowRuntimeManager wfrManager, Guid instanceId, UserEntity fqrEntity, string task_id, string ptask_id, string eventd_name, string eventd_des, string curtask_clyj,
         List<WfInsvalueEntity> wivList, int[] clrs, Dictionary<int, StateMachineWorkflowInstance> wfTempDic, string str_id)
        {
            var frq_staff = bs.QueryStaff(fqrEntity.staff_id);
            //BillServer billserver = (wfrManager.WorkflowRuntime).GetService<ServiceApplication.Service.WorkFlow.BillServer>();

            WfEntity wfEntity = wfDao.QueryEntityByuniqueid(instanceId.ToString());
            WfTaskEntity wftaskEntity = QueryTask(task_id);

            if (clrs == null || clrs.Length == 0)
            {
                //注释原因 如果是按权限处理则一定会传进来clrs，要么是找到对应权限的人，要么是重新指定人

                WfClrxxInfo nextClr = getNextClrxxByTaskName(wfTempDic, wfEntity.wftemplate_id, wftaskEntity.taskname, eventd_des);

                //下一步处理人
                if (nextClr != null && nextClr.clzType == TaskClrType.按权限.ToString())
                {
                    string[] wfspqxnames = nextClr.AsQx;
                    var dt_qx = WfSpqxQuery(wfspqxnames);
                    var arr_qxid = dt_qx.AsEnumerable().Select(s => s.Field<int>("编码")).ToArray();
                    DataTable dt_clr = null;

                    if (!nextClr.IsSelfDept)
                        dt_clr = bs.QueryUserBySpqx(arr_qxid);
                    else
                        dt_clr = bs.QueryUserBySpqxDept(arr_qxid, frq_staff.dept_id);

                    //按职务的类型下如果有多人，则多人抢占式发起
                    if (dt_clr != null && dt_clr.Rows.Count > 0)
                    {
                        clrs = dt_clr.AsEnumerable().Select(d => d.Field<int>("用户编码")).ToArray();
                    }
                    else
                    {
                        return new ResTag(false, "下一步处理人不存在，请确认");
                    }
                }
                else if (nextClr != null && nextClr.clzType == TaskClrType.发起人.ToString())
                {
                    clrs = new int[] { fqrEntity.user_id };
                }
                else if (nextClr != null && nextClr.clzType == TaskClrType.按人员.ToString())
                {
                    clrs = nextClr.clrCode;
                }
            }
            WfTaskEntity wfTaskEntity = TaskDao.Query(task_id);

            #region 事务操作: 先触发工作流，再存入数据库
            TransactionOptions option = new TransactionOptions();
            option.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
            {
                List<WfTaskEntity> taskEntityNewlist = new List<WfTaskEntity>();

                var task_refuse = this.taskRefuse(wfTempDic, wfEntity.wftemplate_id, wftaskEntity.taskname, eventd_des);
                StateMachineWorkflowInstance workflowInstance = wfTempDic[wfEntity.wftemplate_id];

                等待审批提交 waitingHandler = WfUtil.getNextStateEventriven4agree(workflowInstance, wftaskEntity.taskname, eventd_des);
                if (null != waitingHandler)   //暂时用waitingHandler=null 来判断下一步是否是结束状态 2012-09-05 mlh
                {
                    if (!task_refuse)
                    {
                        #region 非驳回流程-数据获取: 新任务实体taskEntityNew
                        WfTaskEntity taskEntity = QueryTask(task_id);
                        if (clrs != null) //如果nextClrInfo.clrCode==null 则说明下一步结束了,待验证 mlh 2011-11-21
                        {
                            for (int i = 0; i < clrs.Length; i++)
                            {
                                taskEntityNewlist.Add(new WfTaskEntity()
                                {
                                    ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
                                    uniqueid = instanceId,
                                    taskname = waitingHandler.Parent.Parent.Name,
                                    state = WfTaskState.TASK_UNDO,
                                    processresult = "",
                                    processtype = waitingHandler.处理人.处理者类型,
                                    processaddition = "无",
                                    user_id = clrs[i],
                                    fqrcode = taskEntity.fqrcode,
                                    starttime = taskEntity.starttime,
                                    checkintime = DateUtil.getStandardTimeBySecond(),
                                    days = 100,
                                    endtime = DateUtil.getStandardTimeBySecond(),
                                    task_clyj = "",
                                    isread = 0
                                });
                            }
                        }
                        else
                        {
                            if (waitingHandler.处理人.处理者类型 == TaskClrType.发起人.ToString())
                            {
                                clrs = new int[] { taskEntity.fqrcode };
                            }
                            else if (null != waitingHandler.处理人.处理人编码)
                            {
                                //获得当前处理人
                                clrs = waitingHandler.处理人.处理人编码;
                            }

                            if (null != clrs)
                            {
                                for (int i = 0; i < clrs.Length; i++)
                                {
                                    taskEntityNewlist.Add(new WfTaskEntity()
                                    {
                                        ptask_id = int.Parse(task_id),//新任务中的ptaskid即是正在处理的任务的taskid
                                        uniqueid = instanceId,
                                        taskname = waitingHandler.Parent.Parent.Name,
                                        state = WfTaskState.TASK_UNDO,
                                        processresult = "",
                                        processtype = waitingHandler.处理人.处理者类型,
                                        processaddition = "无",
                                        user_id = clrs[i],
                                        fqrcode = taskEntity.fqrcode,
                                        starttime = taskEntity.starttime,
                                        checkintime = "",
                                        days = 100,
                                        endtime = "",  //mlh 2011-11-21 + 
                                        task_clyj = "",
                                        isread = 0
                                    });
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region 驳回流程

                        var pre_task = QueryTaskByName(instanceId.ToString(), waitingHandler.Parent.Parent.Name);//taskname从 edact.Parent.Name获取
                        taskEntityNewlist.Add(new WfTaskEntity()
                        {
                            ptask_id = int.Parse(task_id),
                            uniqueid = instanceId,
                            taskname = pre_task.Rows[0]["任务名称"].ToString(),
                            state = WfTaskState.TASK_UNDO,
                            processresult = "",
                            processtype = pre_task.Rows[0]["处理类型"].ToString(),
                            processaddition = pre_task.Rows[0]["处理备注"].ToString(),
                            user_id = Int32.Parse(pre_task.Rows[0]["处理人编码"].ToString()),
                            fqrcode = Int32.Parse(pre_task.Rows[0]["发起人编号"].ToString()),
                            starttime = DateUtil.getStandardTimeBySecond(),
                            checkintime = "",
                            days = 100,
                            endtime = "",
                            task_clyj = "",
                            isread = 0
                        });

                        #endregion
                    }
                    AddTask(taskEntityNewlist);
                    addInsvalue(wivList);
                }
                else  //工作流结束
                {
                    updateInsResult(instanceId.ToString(), "结束", wfrManager);
                }
                string clsj = DateUtil.getStandardTimeBySecond();
                UpdateTask(task_id, ptask_id, instanceId, eventd_des, curtask_clyj, clsj, str_id);//暂时使用eventdriven的description属性作为处理结果
                scope.Complete();
            }
            return new ResTag(true, "操作成功");
            #endregion
        }

        #endregion

        //取消工作流程
        public ResTag DoWfCancel(string task_id, WorkflowRuntimeManager wfrManager)
        {
            var wftaskEntity = QueryTask(task_id);
            var wfinsEntity = queryInsEntity(wftaskEntity.uniqueid.ToString());
            wftaskEntity.state = "废弃";
            wftaskEntity.processresult = "废弃";
            wftaskEntity.endtime = DateUtil.getStandardTimeBySecond();
            try
            {
                UpdateTask(wftaskEntity);
                updateInsResult(wfinsEntity.uniqueid.ToString(), "废弃", wfrManager);
            }
            catch (Exception e)
            {
                return new ResTag(false, "取消失败");
            }
            return new ResTag(true, "操作成功");
        }

        //发起工作流判断处理人
        public WfClrxxInfo getClrxxByFirstNext(Dictionary<int, StateMachineWorkflowInstance> wfTempDic, int templeteCode)
        {
            ChoiceClrxx nextClz = WfUtil.getFirstToNextClxx(wfTempDic, templeteCode);
            if (nextClz == null) return null;
            WfClrxxInfo wfClz = new WfClrxxInfo();
            wfClz.clrCode = nextClz.处理人编码;
            wfClz.clzName = nextClz.处理者名称;
            wfClz.clzType = nextClz.处理者类型;
            wfClz.AsQx = nextClz.按权限;
            wfClz.IsSelfDept = nextClz.本部门;
            return wfClz;
        }

        public Boolean taskRefuse(Dictionary<int, StateMachineWorkflowInstance> wfTempDic,
            int templeteCode, string currentStateName, string description)
        {
            return WfUtil.taskRefuse(wfTempDic, templeteCode, currentStateName, description);
        }

        //处理过程判断处理人
        public WfClrxxInfo getNextClrxxByTaskName(Dictionary<int, StateMachineWorkflowInstance> wfTempDic,
            int templeteCode, string currentStateName, string description)
        {
            ChoiceClrxx nextClz = WfUtil.getNextClxx(wfTempDic, templeteCode, currentStateName, description);
            if (nextClz == null) return null;
            WfClrxxInfo wfClz = new WfClrxxInfo();
            wfClz.clrCode = nextClz.处理人编码;
            wfClz.clzName = nextClz.处理者名称;
            wfClz.clzType = nextClz.处理者类型;
            wfClz.AsQx = nextClz.按权限;
            wfClz.IsSelfDept = nextClz.本部门;
            return wfClz;
        }

        //获取当前state的所有处理步骤，即所有eventdriven 的 name 和description 
        public DataTable getNextStep(StateMachineWorkflowInstance ins, string curStateName)
        {
            StateActivity stateAct = ins.States.Where(x => x.Name == curStateName).First();

            DataTable dt = new DataTable();
            dt.Columns.Add("NID", typeof(string));
            dt.Columns.Add("NTEXT", typeof(string));
            //dt.Rows.Add("-1", "==请选择==");
            int i = 0;
            foreach (Activity act in stateAct.Activities)
            {
                if (act is EventDrivenActivity)
                {
                    EventDrivenActivity edact = (EventDrivenActivity)act;

                    if (edact.EnabledActivities.Count > 0 && edact.EnabledActivities[0] is HandleExternalEventActivity)
                    {
                        dt.Rows.Add(edact.Name, act.Description);
                    }
                }
                i++;
            }
            return dt;
        }


        #region 用于获取wf流程模板的结构映射

        /// <summary>
        ///  遍历工作流实例来获取所有流转线路,注意：一个state有同意和取消就会在返回dt中生成2行
        ///  列名：状态名称，下一步状态名，处理名称，处理类型，
        /// </summary>
        /// <param name="staMacWFI"></param>
        /// <returns></returns>
        public DataTable getWFPlateChart(StateMachineWorkflowInstance staMacWFI)
        {
            DataTable dt = new DataTable();
            DataColumn[] dc = {
                                  new DataColumn("状态名称"),
                                  new DataColumn("下一步状态名"),
                                  new DataColumn("事件名称"),
                                  new DataColumn("事件描述"),
                                  new DataColumn("处理类型"),
                                  new DataColumn("处理人"),
                                  new DataColumn("index"),
                              };
            dt.Columns.AddRange(dc);
            List<DataRow> drs = new List<DataRow>();
            foreach (var item in staMacWFI.States)
            {
                getPlateChartBySate(item, dt);
            }
            //对state进行重新排序
            var first_drs = dt.AsEnumerable().Where(x => x["状态名称"].ToString() == staMacWFI.StateMachineWorkflow.InitialStateName).ToArray();
            var index = 1;
            if (first_drs != null)
            {
                foreach (var item in first_drs)
                {
                    item["index"] = index;
                }
            }
            while (first_drs != null && first_drs.Length > 0)
            {
                first_drs = dt.AsEnumerable().Where(x => x["状态名称"].ToString() == first_drs[0]["下一步状态名"].ToString()).ToArray();
                if (first_drs != null && first_drs.Length > 0)
                {
                    foreach (var item in first_drs)
                    {
                        item["index"] = ++index;
                    }
                }
            }
            var dv = dt.DefaultView;
            dv.Sort = "index";
            dt = dv.ToTable();

            return dt;
        }

        //该方法目前还未考虑到一个状态有多个下一步状态的情况
        private void getPlateChartBySate(StateActivity staAct, DataTable dt)
        {
            foreach (var item in staAct.Activities)
            {
                if (item is EventDrivenActivity)
                {
                    EventDrivenActivity edactItem = item as EventDrivenActivity;
                    //string eventDriQuaName = edactItem.QualifiedName;
                    Activity setStateAct = edactItem.Activities.ToArray().Single(x => x is SetStateActivity);
                    Activity clrAct = edactItem.Activities.ToArray().Single(x => x is HandleExternalEventActivity);
                    if (null != setStateAct && null != clrAct)
                    {
                        string cllx = string.Empty;
                        int[] clrids = null;
                        if (clrAct is 等待审批提交)
                        {
                            cllx = (clrAct as 等待审批提交).处理人.处理者类型;

                            clrids = (clrAct as 等待审批提交).处理人.处理人编码;
                        }
                        else if (clrAct is 取消)
                        {
                            cllx = (clrAct as 取消).处理人.处理者类型;

                            clrids = (clrAct as 取消).处理人.处理人编码;
                        }
                        else if (clrAct is 加签)
                        {
                            cllx = (clrAct as 加签).处理人.处理者类型;

                            clrids = (clrAct as 加签).处理人.处理人编码;
                        }
                        else if (clrAct is 等待)
                        {
                            cllx = (clrAct as 等待).处理人.处理者类型;

                            clrids = (clrAct as 等待).处理人.处理人编码;
                        }
                        string clrs = string.Empty;
                        if (clrids != null)
                            clrs = string.Join(",", bs.QueryUserByIds(clrids.Select(i => i.ToString()).ToArray()).AsEnumerable().Select(x => x.Field<string>("用户名称")).ToArray());
                        DataRow dr = dt.NewRow();
                        dr["状态名称"] = staAct.Name;
                        dr["下一步状态名"] = (setStateAct as SetStateActivity).TargetStateName;
                        dr["事件名称"] = edactItem.Name;
                        dr["事件描述"] = edactItem.Description;
                        dr["处理类型"] = cllx;
                        dr["处理人"] = clrs;
                        dt.Rows.Add(dr);
                    }
                }
            }

        }

        #endregion
        #endregion

        #region 工作流任务
        public string AddTask(WfTaskEntity wfTaskEntity)
        {
            return TaskDao.Add(wfTaskEntity);
        }
        public void AddTask(List<WfTaskEntity> wfTaskEntityList)
        {
            if (wfTaskEntityList.Count == 0) return;
            TaskDao.Add(wfTaskEntityList);
        }

        public void UpdateTask(WfTaskEntity wfTaskEntity)
        {
            TaskDao.Update(wfTaskEntity);
        }
        public void UpdateTask(string taskid, string ptaskid, Guid guid, string processresult, string task_clyj, string clsj, string str_id)
        {
            str_id = str_id ?? "";
            TaskDao.Update(taskid, ptaskid, guid, processresult, task_clyj, clsj, str_id);
        }

        public WfTaskEntity QueryTask(string taskid)
        {
            return TaskDao.Query(taskid);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user_id">发起人id</param>
        /// <param name="state">任务状态</param>
        /// <returns></returns>
        public DataTable QueryTask(string user_id, string state)
        {
            return TaskDao.QueryTask(user_id, state);
        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="user_id">当前用户</param>
        /// <param name="clrid"></param>
        /// <param name="wfname">流程名称</param>
        /// <param name="taskstime"></param>
        /// <param name="tasketime"></param>
        /// <returns></returns>
        public DataTable QueryTaskByCondition(String user_id, String clrid, String wfname, String taskstime, String tasketime, String state)
        {
            var dt = TaskDao.QueryTaskByCondition(user_id, null, wfname, taskstime, tasketime, state);
            string[] arr_uniqueid = null;
            if (!string.IsNullOrEmpty(clrid))
            {
                DataTable tmp = QueryTask(clrid, null);
                arr_uniqueid = tmp.AsEnumerable().Select(x => x.Field<Guid>("实例标识").ToString()).Distinct().ToArray();
                var arr_res_uniqueid = dt.AsEnumerable().Select(x => x.Field<Guid>("实例标识").ToString()).Distinct().ToArray();
                var com_uniqueid = arr_res_uniqueid.Intersect(arr_uniqueid);

                if (com_uniqueid.Count() > 0)
                {
                    var drs = from row in dt.AsEnumerable()
                              where com_uniqueid.Contains(row.Field<Guid>("实例标识").ToString())
                              select row;
                    var dt_res = dt.Clone();
                    foreach (var item in drs)
                    {
                        dt_res.ImportRow(item);
                    }
                    return dt_res;
                }
                else
                {

                    return dt.Clone();
                }
            }

            return dt;
        }

        public DataTable QueryTaskFinish(String user_id, String clrid, String wfname, String taskstime, String tasketime, String state)
        {
            var dt = TaskDao.QueryTaskFinish(user_id, null, wfname, taskstime, tasketime, state);
            string[] arr_uniqueid = null;
            if (!string.IsNullOrEmpty(clrid))
            {
                DataTable tmp = QueryTask(clrid, null);
                arr_uniqueid = tmp.AsEnumerable().Select(x => x.Field<Guid>("实例标识").ToString()).Distinct().ToArray();
                var arr_res_uniqueid = dt.AsEnumerable().Select(x => x.Field<Guid>("实例标识").ToString()).Distinct().ToArray();
                var com_uniqueid = arr_res_uniqueid.Intersect(arr_uniqueid);

                if (com_uniqueid.Count() > 0)
                {
                    var drs = from row in dt.AsEnumerable()
                              where com_uniqueid.Contains(row.Field<Guid>("实例标识").ToString())
                              select row;
                    var dt_res = dt.Clone();
                    foreach (var item in drs)
                    {
                        dt_res.ImportRow(item);
                    }
                    return dt_res;
                }
                else
                {

                    return dt.Clone();
                }
            }

            return dt;
        }


        public DataTable QueryTask(string user_id, string state, string clrid, string st, string et)
        {
            var dt = TaskDao.QueryTask(user_id, state);

            for (int i = 0; i < dt.Rows.Count; i++)
            {

                bool flag = false;

                //time 过滤
                var time = DateTime.Parse(dt.Rows[i]["完成时间"].ToString());
                if (!string.IsNullOrEmpty(st))
                {
                    if (time < DateTime.Parse(st))
                    {
                        dt.Rows.RemoveAt(i);
                        i--;
                        continue;
                    }
                }
                if (!string.IsNullOrEmpty(et))
                {
                    if (time > DateTime.Parse(et))
                    {
                        dt.Rows.RemoveAt(i);
                        i--;
                        continue;
                    }
                }
                if (!string.IsNullOrEmpty(clrid))
                {
                    //clrid 过滤
                    var uniqueid = dt.Rows[i]["实例标识"].ToString();
                    var tempDT = TaskDao.QueryTaskByUniqueId(uniqueid);
                    for (int j = 0; j < tempDT.Rows.Count; j++)
                    {
                        if (tempDT.Rows[j]["处理人编码"].ToString() == clrid)
                        {
                            flag = true;
                        }
                    }
                    if (!flag)
                    {
                        dt.Rows.RemoveAt(i);
                        i--;
                    }
                }
            }
            dt.AcceptChanges();
            return dt;
        }

        public DataTable QueryTaskByLoginid(string loginid, string state)
        {
            return TaskDao.QueryTaskByLoginid(loginid, state);
        }

        //查询所有委托人对应的当前任务
        public DataTable QueryTaskByWtrIds(int[] deleg_wtrs)
        {
            return TaskDao.QueryByWtrIds(deleg_wtrs);
        }

        public DataTable QueryTaskByuniqueId(string uniqueId)
        {
            return TaskDao.QueryTaskByUniqueId(uniqueId);
        }

        public DataTable QueryTaskForPlan(string user_id, string state)
        {
            return TaskDao.QueryTaskByWfType(user_id, state, "计划");
        }

        public DataTable QueryTaskByName(String uniqueId, String taskName)
        {
            return TaskDao.QueryTaskByName(uniqueId, taskName);
        }

        public DataTable QueryTaskSpjgByUniqueId(string uniqueid)
        {
            return TaskDao.QueryTaskSpjgByUniqueId(uniqueid);
        }

        public DataTable QueryTaskSpjgByTwo(string uniqueid, string taks_id)
        {
            return TaskDao.QueryTaskSpjgByTwo(uniqueid, taks_id);
        }
        #endregion

        #region 工作流
        /// <summary>
        /// 
        /// </summary>
        /// <param name="wfEntity"></param>
        /// <returns>自增主键</returns>
        public int AddWf(WfEntity wfEntity)
        {
            return wfDao.AddEntity(wfEntity);
        }

        public void UpdateWf(WfEntity wfEntity)
        {
            wfDao.UpdateEntity(wfEntity);
        }

        public void DeleteWf(int wf_id)
        {
            wfDao.DleteEntity(wf_id);
        }

        public WfEntity QueryWf(string wf_id)
        {
            return wfDao.QueryEntity(wf_id);
        }

        public WfEntity QueryWfByuniqueid(string uniqueid)
        {
            return wfDao.QueryEntityByuniqueid(uniqueid);
        }

        /// <summary>
        /// 查询所有工作流
        /// </summary>
        /// <returns></returns>
        public DataTable QueryAllWf()
        {
            return wfDao.QueryAllWf();
        }

        public DataTable QueryAllWfByState(int status)
        {
            return wfDao.QueryAllWf(status);
        }

        public DataTable QueryWfByType(string wftype_name)
        {
            return wfDao.QueryByType(wftype_name);
        }

        #endregion

        #region 工作流模板

        public int addWfTemplate(WfTemplateEntity wfModuleEntity)
        {
            return wfTemplateDao.AddEntity(wfModuleEntity);
        }

        public void updateWfTemplate(WfTemplateEntity wfModuleEntity)
        {
            wfTemplateDao.UpdateEntity(wfModuleEntity);
        }

        public void deleteWfTemplate(int wfModule_id)
        {
            wfTemplateDao.DleteEntity(wfModule_id);
        }

        public DataTable QueryWfTemplate()
        {
            return wfTemplateDao.QueryAll();
        }

        public Dictionary<int, StateMachineWorkflowInstance> QueryPlateList(WorkflowRuntimeManager wfrManger)
        {
            Dictionary<int, StateMachineWorkflowInstance> plateList = new Dictionary<int, StateMachineWorkflowInstance>();
            var dt = QueryWfTemplate();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int wftemplate_id = int.Parse(dt.Rows[i][0].ToString());
                TextReader t1 = new StringReader(dt.Rows[i][2].ToString());
                TextReader t2 = new StringReader(dt.Rows[i][3].ToString());
                XmlReader define = XmlReader.Create(t1);
                XmlReader rule = XmlReader.Create(t2);

                var ins = wfrManger.WorkflowRuntime.CreateWorkflow(define, rule, null);
                var stateMachineWorkflowInstance = new
                       StateMachineWorkflowInstance(wfrManger.WorkflowRuntime, ins.InstanceId);
                plateList.Add(wftemplate_id, stateMachineWorkflowInstance);
            }
            return plateList;
        }

        public WfTemplateEntity QueryWfTemplate(int wftemplate_id)
        {
            return wfTemplateDao.QueryEntity(wftemplate_id);
        }


        #endregion

        #region 工作流实例

        public void addIns(WfInsEntity wfinsEntity)
        {
            wfInsDao.addIns(wfinsEntity);
        }

        public void updateInsResult(string uniqueid, string result, WorkflowRuntimeManager wfrMang)
        {
            wfInsDao.updateInsResult(uniqueid, result);
            try
            {
                var wfinstance = wfrMang.WorkflowRuntime.GetWorkflow(new Guid(uniqueid));
                if (wfinstance != null)
                    wfinstance.Terminate(result);
            }
            catch
            {

            }
        }

        /// <summary>
        /// 获取该user所发起的所有实例
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public DataTable queryIns(string user_id)
        {
            return wfInsDao.queryIns(user_id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="clrid"></param>
        /// <param name="wfname"></param>
        /// <param name="taskstime"></param>
        /// <param name="tasketime"></param>
        /// <param name="state">例如： " '处理中','未处理','开始','废弃' "</param>
        /// <returns></returns>
        public DataTable queryStartListByConditions(String user_id, String clrid, String wfname, String taskstime, String tasketime, string state)
        {
            var dt = wfInsDao.queryInsByCondition(user_id, null, wfname, taskstime, tasketime, state);
            string[] arr_uniqueid = null;
            if (!string.IsNullOrEmpty(clrid))
            {
                DataTable tmp = QueryTask(clrid, null);
                arr_uniqueid = tmp.AsEnumerable().Select(x => x.Field<Guid>("实例标识").ToString()).Distinct().ToArray();
                var arr_res_uniqueid = dt.AsEnumerable().Select(x => x.Field<Guid>("唯一标识").ToString()).Distinct().ToArray();
                var com_uniqueid = arr_res_uniqueid.Intersect(arr_uniqueid);

                if (com_uniqueid.Count() > 0)
                {
                    var drs = from row in dt.AsEnumerable()
                              where com_uniqueid.Contains(row.Field<Guid>("唯一标识").ToString())
                              select row;
                    var dt_res = dt.Clone();
                    foreach (var item in drs)
                    {
                        dt_res.ImportRow(item);
                    }
                    return dt_res;
                }
                else
                {

                    return dt.Clone();
                }
            }
            return dt;
        }

        public WfInsEntity queryInsEntity(string uniqueid)
        {
            return wfInsDao.queryInsEntity(uniqueid);
        }

        public void PersistenceInstanceClear()
        {
            wfInsDao.PersistenceInstanceClear();
        }

        #region 计划

        public DataTable queryPlan(string creater_id)
        {
            return wfInsDao.queryPlan(creater_id, "计划");
        }

        public DataTable queryPlanDetial(string ins_id)
        {
            return wfInsDao.queryPlanByInsid(ins_id);
        }


        #endregion
        #endregion

        #region 工作流实例值
        WfInsvalueDao wfInsvalueDao = new WfInsvalueDao();
        public void addInsvalue(List<WfInsvalueEntity> wfiveList)
        {
            if (wfiveList.Count == 0) return;
            wfInsvalueDao.AddEntity(wfiveList);
        }
        public void UpdateInsvalue()
        {

        }
        public void DeleteInsvalue()
        {

        }
        public List<WfInsvalueEntity> QueryInsvalue(string task_id)
        {
            return wfInsvalueDao.QueryEntity(task_id);
        }


        #endregion

        #region 工作流类型

        WftypeDao wftypeDao = new WftypeDao();
        public void AddWfType(WfTypeEntity wftypeEntity)
        {
            wftypeDao.AddEntity(wftypeEntity);
        }

        public void UpdateWfType(WfTypeEntity wftypeEntity)
        {
            wftypeDao.UpadateEntity(wftypeEntity);
        }

        public WfTypeEntity QueryWfType(int wftype_id)
        {
            return wftypeDao.QueryEntity(wftype_id);
        }

        public DataTable QueryWftypeAll()
        {
            return wftypeDao.QueryAll();
        }

        #endregion

        #region 工作流委托
        WfDelegDao wfDelegDao = new WfDelegDao();
        public void AddWfDeleg(WfDelegEntity wfDelegEntity)
        {
            wfDelegDao.AddEntity(wfDelegEntity);
        }

        public void UpdateWfDeleg(WfDelegEntity wfDelegEntity)
        {
            wfDelegDao.UpadateEntity(wfDelegEntity);
        }

        public WfDelegEntity QueryWfDeleg(int deleg_id)
        {
            var wfDelegEntity = wfDelegDao.QueryEntity(deleg_id);
            return wfDelegEntity;
        }

        /// <summary>
        /// 查询当前用户的有效委托、如果范围为null则说明当前无有效委托
        /// </summary>
        /// <param name="deleg_wtr"></param>
        /// <returns></returns>
        public WfDelegEntity QueryWfDelegCur(int deleg_wtr)
        {
            WfDelegEntity wfDelegEntity = wfDelegDao.QueryCurActiviy(deleg_wtr);
            return wfDelegEntity;
        }

        public DataTable QueryWfDelegByStrId(int deleg_str)
        {
            var dt = wfDelegDao.QueryByStrId(deleg_str);
            return dt;
        }

        public DataTable QueryWfDelegByWtrId(int deleg_wtr)
        {
            var dt = wfDelegDao.QueryByWtrId(deleg_wtr);
            return dt;
        }

        /// <summary>
        /// 查询所有当前有效委托
        /// </summary>
        /// <returns></returns>
        public DataTable QueryWfDelegValid()
        {
            var dt = wfDelegDao.QueryCurValid();
            return dt;
        }


        #endregion

        #region 工作流审批权限
        WfSpqxDao wfspqxDao = new WfSpqxDao();
        public int WfSpqxAdd(WfSpqxEntity wfspqxEntity)
        {
            return wfspqxDao.AddEntity(wfspqxEntity);
        }

        public void WfSpqxDelete(int spqx_id)
        {
            wfspqxDao.DeleteEntity(spqx_id);
        }


        public void WfSpqxUpdate(WfSpqxEntity wfspqxEntity)
        {
            wfspqxDao.UpdateEntity(wfspqxEntity);
        }

        public WfSpqxEntity WfSpqxQuery(int spqx_id)
        {
            return wfspqxDao.QueryEntity(spqx_id);
        }

        public DataTable WfSpqxQuery(string[] spqx_names)
        {
            if (spqx_names == null || spqx_names.Length == 0) return null;
            return wfspqxDao.QueryEntity(spqx_names);
        }
        public DataTable WfSpqxQueryAll()
        {
            return wfspqxDao.QueryAll(-1);
        }
        public DataTable WfSpqxQueryAll(int spqx_kybz)
        {
            return wfspqxDao.QueryAll(spqx_kybz);
        }
        #endregion

        #region 审批权限对应表

        SpqxdybDao spqxdybDao = new SpqxdybDao();
        public int SpqxdybAdd(SpqxdybEntity spqxdybEntity)
        {
            return spqxdybDao.AddEntity(spqxdybEntity);
        }
        public void SpqxdybUpdateBySpqxId(int spqx_id, string[] user_ids)
        {
            //删除以前的
            SpqxdybDeleteBySpqxId(spqx_id);
            //更新或者添加
            if (user_ids.Length > 0)
            {
                foreach (var item in user_ids)
                {
                    var entity = new SpqxdybEntity() { spqxdyb_id = -1, spqx_id = spqx_id, user_id = int.Parse(item) };
                    spqxdybDao.AddEntity(entity);
                }
            }
        }
        public void SpqxdybUpdateByUserId(string[] spqx_ids, int user_id)
        {
            //删除以前的
            SpqxdybDeleteByUserId(user_id);
            //更新或者添加
            if (spqx_ids.Length > 0)
            {
                foreach (var item in spqx_ids)
                {
                    var entity = new SpqxdybEntity() { spqxdyb_id = -1, spqx_id = int.Parse(item), user_id = user_id };
                    spqxdybDao.AddEntity(entity);
                }
            }
        }
        public void SpqxdybDeleteBySpqxId(int spqx_id)
        {
            spqxdybDao.DeleteBySpqxId(spqx_id);
        }
        public void SpqxdybDeleteByUserId(int user_id)
        {
            spqxdybDao.DeleteByUserId(user_id);
        }
        public void SpqxdybUpdate(SpqxdybEntity spqxdybEntity)
        {
            spqxdybDao.UpdateEntity(spqxdybEntity);
        }
        public SpqxdybEntity SpqxdybQuery(int spqxdyb_id)
        {
            return spqxdybDao.QueryEntity(spqxdyb_id);
        }

        /// <summary>
        /// 参数可填可空
        /// </summary>
        /// <param name="spqx_id"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public DataTable SpqxdybQuery(string spqx_id, string user_id)
        {
            return spqxdybDao.Query(spqx_id, user_id);
        }

        public DataTable SpqxdybQueryAll()
        {
            return spqxdybDao.QueryAll();
        }
        #endregion

        // 查询 绑定参数
        public String getsqlargs(String uniqueid)
        {
            return wfInsDao.getInsargs(uniqueid);
        }

        public DataTable QueryTaskByRead(String userId, Int32 read)
        {
            return TaskDao.QueryTaskByRead(userId, read);
        }

        public void ConfirmUnreadTask(String taskId)
        {
            TaskDao.ConfirmUnreadTask(taskId);
        }
    }
}
